package com.sky.websocket;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.context.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint(value = "/ws/{sid}")
@Component
@Slf4j
public class WebSocketServer {

    private static final Map<String,Session> sessionMap = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session, @PathParam("sid") String sid){
        log.info("建立websocket连接:{}",session);
        sessionMap.put(sid,session);

    }

    @OnMessage
    public void onMessage(String message){

    }

    @OnClose
    public void onClose(Session session,@PathParam("sid") String sid){
        log.info("用户退出");
        sessionMap.remove(sid);
    }


    /**
     * 广播消息
     * @param message
     */
    public void broadCast(String message){
        try {
        // 遍历map集合
        Set<Map.Entry<String, Session>> entries = sessionMap.entrySet();
        for (Map.Entry<String,Session> entry : entries) {
            // 获取到所有用户对应的session对象
            Session session = entry.getValue();
            // 发送消息
            session.getBasicRemote().sendText(message);
        }
            } catch (Exception e) {
                log.info("广播消息异常:{}",e.getMessage());
        }
    }
}
